package database

import (
	"fmt"
	"sync"

	"gorm.io/gorm"
)

type RepositoryRegisterItem struct {
	RepoName string
	RepoFunc func(db *gorm.DB) Repository
}

type RepoRegisterMap map[string]Repository

type Manager struct {
	db          *gorm.DB
	registerMap RepoRegisterMap
	mu          sync.RWMutex
}

func NewManager(db *gorm.DB) *Manager {
	return &Manager{
		db:          db,
		registerMap: make(RepoRegisterMap),
	}
}
func (m *Manager) Register(items ...RepositoryRegisterItem) error {
	for _, item := range items {

		if _, exists := m.registerMap[item.RepoName]; exists {
			return fmt.Errorf("repository '%s' already registered", item.RepoName)
		}
		m.mu.Lock()
		m.registerMap[item.RepoName] = item.RepoFunc(m.db)
		m.mu.Unlock()
	}
	return nil
}

func (m *Manager) Get(repoName string) (Repository, error) {
	repo, ok := m.registerMap[repoName]
	if !ok {
		return nil, fmt.Errorf("[RepositoryManager] get repo failed, repoName: %s not registered", repoName)
	}
	return repo, nil
}
